package br.com.musclebook.bean.wizard.routine;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import br.com.musclebook.bean.SessionInfoBean;
import br.com.musclebook.entity.Exercise;
import br.com.musclebook.entity.ExerciseExecutionSet;
import br.com.musclebook.entity.RoutineDay;
import br.com.musclebook.entity.RoutineDayTraining;
import br.com.musclebook.service.ExerciseService;

@Named
@ViewScoped
public class ExerciseSelectionBean implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private SessionInfoBean sessionInfoBean;

    @Inject
    private RoutineWizardBean routineWizardBean;

    @Inject
    private ExerciseService exerciseService;

    private RoutineDayTraining routineDayTraining;

    private ExerciseExecutionSet selectedExercise;

    private List<Exercise> exercises;
    
    @PostConstruct
    public void init() {
	this.selectedExercise = new ExerciseExecutionSet();
    }

    public String search() {
	this.selectedExercise = new ExerciseExecutionSet();
	this.selectedExercise.setRoutineDayTraining(this.routineDayTraining);
	this.exercises = this.exerciseService.listByCategory(this.routineDayTraining.getExerciseCategory(), this.sessionInfoBean.getUserId());

	for (RoutineDay rDay : this.routineWizardBean.getRoutine().getRoutineDays()) {
	    if (rDay.getDayOfWeek().equals(this.routineDayTraining.getRoutineDay().getDayOfWeek())) {
		for (RoutineDayTraining training : rDay.getRoutineDayTrainings()) {
		    if (training.getExerciseCategory().equals(this.routineDayTraining.getExerciseCategory())) {
			for (ExerciseExecutionSet execSet : training.getExerciseExecutionSets()) {
			    for (Iterator<Exercise> it = this.exercises.iterator(); it.hasNext();) {
				Exercise exerc = it.next();
				if (exerc.getId().equals(execSet.getExercise().getId())) {
				    it.remove();
				    break;
				}
			    }
			}
		    }
		}
	    }
	}
	return null;
    }

    public List<Exercise> getExercises() {
	return exercises;
    }

    public void setExercises(List<Exercise> exercises) {
	this.exercises = exercises;
    }

    public ExerciseExecutionSet getSelectedExercise() {
	return selectedExercise;
    }

    public void setSelectedExercise(ExerciseExecutionSet selectedExercise) {
	this.selectedExercise = selectedExercise;
    }

    public RoutineDayTraining getRoutineDayTraining() {
        return routineDayTraining;
    }

    public void setRoutineDayTraining(RoutineDayTraining routineDayTraining) {
        this.routineDayTraining = routineDayTraining;
    }

}
